package utils

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"myproject/model"
	"net/http"
	"net/url"
	"time"
)

// 发布开户信息到银行存管平台
func TestOpen() {
	//一直在执行的任务
	//从redis中读取任务
	//查询信息
	//调用银行存管平台接口
	r := RedisPool
	for {
		//获取长度，判断队列中是否有信息
		len := r.ListLen("openuser")
		if len > 0 {
			//从队列中取一个信息l.ListRange(key,start,end)
			openId := r.ListPop("openuser")
			// 获取数据库中的数据
			open_info := &model.OpenBank{}
			model.GetDb().Find(open_info, "id=?", openId)
			// 定义切片
			data := make(map[string]interface{})
			data["name"] = open_info.Name
			data["userid"] = open_info.Userid

			// 获取token
			token := openToekn(data)

			// 申请开户
			code := openUser(token, open_info.CardNumber, open_info.BankCode, open_info.Name)
			db := model.GetDb()
			sql := "update open_banks set status=? where id=?"
			if code == 200 {
				// 更新状态
				db.Exec(sql, 1, openId)
				fmt.Println("===已通过审核===")
			} else {
				// 更新状态
				db.Exec(sql, 0, openId)
				fmt.Println("---未通过审核---")
			}

		}
		fmt.Println(time.Now())
		time.Sleep(time.Second * 60)
	}
}

// 获取token
func openToekn(datas map[string]interface{}) string {
	var host = "http://127.0.0.1:5000/token"
	var param = map[string]string{
		"name":    fmt.Sprint(datas["name"]),
		"appname": "p2p",
		"userid":  fmt.Sprint(datas["userid"]),
	}

	uri, err := url.Parse(host)
	if err != nil {
		fmt.Println(err)
	}
	query := uri.Query()
	for k, v := range param {
		query.Set(k, v)
	}
	uri.RawQuery = query.Encode()

	response, err := http.Get(uri.String())
	if err != nil {
		fmt.Println(err)
	}
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
	}
	//fmt.Println(">>", string(result))

	var v interface{}
	_ = json.Unmarshal([]byte(string(result)), &v)
	data := v.(map[string]interface{})

	return data["token"].(string)
}

// 开户申请
func openUser(token, card_number, bank_code, name string) float64 {
	var host = "http://127.0.0.1:5000/apply"
	var param = map[string]string{
		"token":       fmt.Sprint(token),
		"card_number": card_number,
		"bank_code":   bank_code,
		"name":        name,
	}

	uri, err := url.Parse(host)
	if err != nil {
		fmt.Println(err)
	}
	query := uri.Query()
	for k, v := range param {
		query.Set(k, v)
	}
	uri.RawQuery = query.Encode()

	response, err := http.Get(uri.String())
	if err != nil {
		fmt.Println(err)
	}
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(">>", string(result))
	fmt.Printf("type: %T\n", result)

	var v interface{}
	_ = json.Unmarshal([]byte(string(result)), &v)
	data := v.(map[string]interface{})
	fmt.Println(data["code"])

	return data["code"].(float64)

}
